package com.by.yz.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.NetworkImageView;
import com.by.yz.App;
import com.by.yz.R;
import com.by.yz.Register.DoctorREST;
import com.by.yz.activity.base.BaseActivity;
import com.by.yz.adapter.GridAdapter;
import com.by.yz.custom.MyGridView;
import com.by.yz.custom.TechnologyTeamDividerItemDecoration;
import com.by.yz.entity.Department;
import com.by.yz.entity.Hospital;

import com.by.yz.loginUtil.DepartmentRESTFul;
import com.by.yz.loginUtil.HospitalRESTFul;
import com.by.yz.util.IsNetWork;
import com.by.yz.util.ToJSonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lupeng on 2017/3/18.
 */
public class FamousDoctor extends BaseActivity implements View.OnClickListener{

    private EditText look_auto;
    private TextView search;  //查找
    private String text;
    private RecyclerView resultListview;
    String seriesName="";
    List<Hospital> datas=new ArrayList<Hospital>();
    private static int oldnum;
    private static int num;
    private static int keshiNum;
    private static List<String> keshiName;
    IsNetWork isNetWork;
    SimpleStringRecyclerViewAdapter asd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e("--onCreate--","onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.famous_doctor);
        setToolbarTitle("名医馆");
//        datas=new ArrayList<Hospital>();
        asd = new SimpleStringRecyclerViewAdapter(this,datas);;
        initView();
        initDatas();
    }

    private void initView() {
        Log.e("--initView--","initView");
        look_auto = (EditText) findViewById(R.id.look_auto);
        search = (TextView) findViewById(R.id.lv_look);
        search.setOnClickListener(this);
        resultListview=(RecyclerView) findViewById(R.id.result_listview);
        resultListview.setLayoutManager(new LinearLayoutManager(resultListview.getContext()));
        resultListview.setAdapter(asd );
        resultListview.addItemDecoration(new TechnologyTeamDividerItemDecoration(this,TechnologyTeamDividerItemDecoration.VERTICAL_LIST));
    }

    private void initDatas(){
        keshiName =new ArrayList<String>();
        Log.e("--initDatas--","initDatas");
        seriesName = getIntent().getStringExtra("searchString");
        HospitalRESTFul hospitalREST=new HospitalRESTFul();
        hospitalREST.getAllHospitals(new HospitalRESTFul.MyGETCallBack() {
            @Override
            public void ok(JSONArray response) throws JSONException {
                for (int i = 0; i < response.length(); i++) {
                    Hospital hospital;
                    JSONObject jsonObject = response.getJSONObject(i);
                    hospital = ToJSonObject.jsonToBean(jsonObject.toString(),Hospital.class);
                    if(hospital.getHospital().toString().equals(seriesName) || seriesName.toString().equals("")) {
                        datas.add(hospital);
                        resultListview.setVisibility(View.VISIBLE);
                    }
                }
            }
            @Override
            public void error(String error) {
                Log.e("error","error2");
            }
        });
        DepartmentRESTFul DepartmentREST=new DepartmentRESTFul();
        DepartmentREST.getAllDepartments(new DepartmentRESTFul.MyGETCallBack() {
            @Override
            public void ok(JSONArray response) throws JSONException {
                keshiNum = response.length();
                for (int i = 0; i < keshiNum; i++) {
                    Department department;
                    JSONObject jsonObject = response.getJSONObject(i);
                    department = ToJSonObject.jsonToBean(jsonObject.toString(), Department.class);
                    keshiName.add(i,department.getDepartment());
                }
                Log.e("keshiNum",keshiNum+"");
            }
            @Override
            public void error(String error) {
                Log.e("error",error);
            }
        });
    }

    public static class SimpleStringRecyclerViewAdapter
            extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {

        private final TypedValue mTypedValue = new TypedValue();
        private int mBackground;
        private List<Hospital> mValues;
        private int currentItem = -1;
        private static Context con;
        private static GridAdapter adapter;
        private static List<Map<String,Object>> list;

        public static class ViewHolder extends RecyclerView.ViewHolder {
            public Hospital tt;
//            public final ImageView mImageView;
            public final TextView hospitalName;
            private LinearLayout mView;
            private MyGridView gv;

            public ViewHolder(final View view) {
                super(view);
                mView = (LinearLayout) view.findViewById(R.id.find_hospital_result_item);
//                mImageView = (ImageView) view.findViewById(R.id.avatar);
                hospitalName = (TextView) view.findViewById(R.id.hospitalName);
                gv = (MyGridView) view.findViewById(R.id.keshiView);
            }

        }

        public Hospital getValueAt(int position) {
            return mValues.get(position);
        }

        public SimpleStringRecyclerViewAdapter(Context context, List< Hospital> items) {
            con = context;
            context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
            mBackground = mTypedValue.resourceId;
            mValues = items;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.famous_doctor_result, parent, false);
            // view.setBackgroundResource(mBackground);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, final int position) {
            holder.tt = mValues.get(position);
            holder.hospitalName.setText(mValues.get(position).getHospital());
            list = new ArrayList<Map<String,Object>>();
            Bundle b = new Bundle();
            try{Map<String,Object> map = null;
                for(int i=0;i<keshiNum;i++){
                    map = new HashMap<String,Object>();
                    map.put("yiyuan", mValues.get(position).getHospital());
                    map.put("text", keshiName.get(i));
                    map.put("Type", 3);
                    list.add(map);
                }
            }catch(Exception e){
                Log.e("Exception = ",e.toString());
            }finally{
                adapter = new GridAdapter(con,list);
                holder.gv.setAdapter(adapter);
            }
//            gridList(holder,position);
            if (currentItem == position) {
                holder.gv.setVisibility(View.VISIBLE);
            } else {
                holder.gv.setVisibility(View.GONE);
            }
            holder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //用 currentItem 记录点击位置
                    int tag = position;
                    if (tag == currentItem) { //再次点击
                        currentItem = -1; //给 currentItem 一个无效值
                    } else {
                        currentItem = tag;
                    }
                    //通知adapter数据改变需要重新加载,必须有的一步
                    notifyDataSetChanged();
                }
            });
        }
        void  gridList(final ViewHolder holder, final int position){
            Bundle b = new Bundle();
            try{Map<String,Object> map = null;
                for(int i=0;i<keshiNum;i++){
                    map = new HashMap<String,Object>();
                    map.put("yiyuan", mValues.get(position).getHospital());
                    map.put("text", keshiName.get(i));
                    map.put("Type", 3);
                    list.add(map);
                }
            }catch(Exception e){
                Log.e("Exception = ",e.toString());
            }finally{
                adapter = new GridAdapter(con,list);
                holder.gv.setAdapter(adapter);
            }
        }

        @Override
        public int getItemCount() {
            return mValues.size();
        }

    }
    private void openSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(look_auto,InputMethodManager.SHOW_FORCED);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lv_look:
                text = look_auto.getText().toString().trim();

                HospitalRESTFul hospitalREST=new HospitalRESTFul();
                hospitalREST.getAllHospitals(new HospitalRESTFul.MyGETCallBack() {
                        @Override
                        public void ok(JSONArray response) throws JSONException {
                            datas.clear();
                            boolean flag = true;

                            if (text.equals("")) {
                                Log.e("--find--","获取全部");
                                flag = false;
                                for (int i = 0; i < response.length(); i++) {
                                    Hospital hospital;
                                    JSONObject jsonObject = response.getJSONObject(i);
                                    hospital = ToJSonObject.jsonToBean(jsonObject.toString(), Hospital.class);
                                    datas.add(hospital);
                                    resultListview.setVisibility(View.VISIBLE);
                                    openSoftInput();
                                }
                            }else{
                                for (int i = 0; i < response.length(); i++) {
                                    Hospital hospital;
                                    JSONObject jsonObject = response.getJSONObject(i);
                                    hospital = ToJSonObject.jsonToBean(jsonObject.toString(), Hospital.class);
                                    if (hospital.getHospital().toString().indexOf(text) != -1) {
                                        Log.e("--find--", "获取一条数据");
                                        flag = false;
                                        datas.add(hospital);
                                        resultListview.setVisibility(View.VISIBLE);
                                        openSoftInput();
                                    } else {
                                        Log.e("--find--", "跳过一条数据");
                                    }
                                }
                            }
                            asd.notifyDataSetChanged();

                            if(flag){
                                Log.e("--none--","没有搜索到对应信息");
                                resultListview.setVisibility(View.GONE);
                            }
                        }
                        @Override
                        public void error(String error) {
                            Log.e("error","error2");
                        }
                    });
                break;
        }
    }
}
